//
//  LoginViewController.m
//  GimCloud
//
//  Created by Q A on 13-6-29.
//  Copyright (c) 2013年 QA. All rights reserved.
//

#import "UserLoginViewController.h"

#import "NSKeyedArchiverUserLogin.h"
#import "ServiceConnect.h"
#import "NSDictionary+DataFormat.h"
#import "AESCrypt.h"
#import "DspMD5Util.h"

#import "MainBodyViewController.h"
#import "NetworkSettingViewController.h"
#import "JPushHttpService.h"

@interface UserLoginViewController ()

@property (nonatomic,weak) JGProgressHUD *HUD;

@end

@implementation UserLoginViewController

@synthesize userTextField = _userTextField;
@synthesize passTextField = _passTextField;
@synthesize loginButton = _loginButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    _userTextField = nil;
    _passTextField = nil;
    _loginButton = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //状态栏字体改变
    self.loginButton.layer.cornerRadius = 24;
    self.loginButton.layer.masksToBounds = YES;
    
    //设置光标颜色
    _userTextField.tintColor = ThemeColorBlue;
    _passTextField.tintColor = ThemeColorBlue;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    if (!self.navigationController.navigationBarHidden)
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    //设置公司名称
    ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
    self.companyLabel.text = model.organization;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.navigationController.navigationBarHidden)
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)connectNetworkBeforeChecking
{
    if ([_userTextField.text isEqualToString:@""]) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请输入用户名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
    } else if ([_passTextField.text isEqualToString:@""]) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请输入密码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
    } else {
        //连接网络，拉取数据
        [self connectNetworkWebServerGetData];
    }
}


/**
 WebServer登录方式
 */
- (void)connectNetworkWebServerGetData
{
    self.HUD = [self showSimpleHUDText:@"正在登录中"];
    ConfigurationCodeing *configuration = [ConfigurationHelper getConfigurationData];
    
    NSString *userInfo = _userTextField.text;
    NSString *password = [AESCrypt encrypt:_passTextField.text];
    
    //登录类型 0:Web-PC 1:Android-Mobile 2:IOS-Mobile
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userInfo forKey:@"username"];
    [model setValue:password forKey:@"password"];
    [model setValue:@2 forKey:@"apptype"];
    [model setValue:configuration.briefCode forKey:@"CustomerCode"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_userLogin" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.HUD dismissAnimated:YES];
        [self loginInfoProcess:result.resultArray];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        [self.HUD dismissAnimated:YES];
        NSString *errorInfo = @"登录失败，请尝试再次登录";
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:errorInfo delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        [self.HUD dismissAnimated:YES];
        NSString *errorInfo = @"登录失败，请尝试再次登录";
        if(error && error.code == 1) errorInfo = @"登录失败，请检测网络连接";
        if(error && error.code == 2) errorInfo = @"哎呀！服务器好像罢工了";
        
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:errorInfo delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
    }];
}

/**
 登录数据处理
 @param results 返回j登录结果
 */
- (void)loginInfoProcess:(NSArray*)results
{
    
    NSString *errorInfo = nil;
    if (!(results && results.count>0)){
        errorInfo = @"登录失败，请尝试再次登录";
    } else {
        NSDictionary *itemsDictionary = [results firstObject];
        errorInfo = [itemsDictionary objectFormatForKey:@"Error"];
        if (!errorInfo) {
            [self saveUserLoginInfo:itemsDictionary];
            return;
        }
    }
    
    //登录失败提示
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:errorInfo delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

- (void)saveUserLoginInfo:(NSDictionary *)userInfo
{
    UserLoginNSCoding *kUserInfo = [[UserLoginNSCoding alloc] init];
    kUserInfo.Id = [userInfo objectFormatStringForKey:@"id"];
    kUserInfo.username = [userInfo objectFormatStringForKey:@"username"];
    kUserInfo.loginName = [userInfo objectFormatStringForKey:@"loginName"];
    kUserInfo.Name = [userInfo objectFormatStringForKey:@"name"];
    kUserInfo.CorpId = [userInfo objectFormatStringForKey:@"corpId"];
    kUserInfo.CorpName = [userInfo objectFormatStringForKey:@"corpName"];
    kUserInfo.DeptId = [userInfo objectFormatStringForKey:@"deptId"];
    kUserInfo.DeptName = [userInfo objectFormatStringForKey:@"deptName"];
    kUserInfo.PostId = [userInfo objectFormatStringForKey:@"postId"];
    kUserInfo.PostName = [userInfo objectFormatStringForKey:@"postName"];
    kUserInfo.RoleId = [userInfo objectFormatStringForKey:@"roleId"];
    kUserInfo.RoleName = [userInfo objectFormatStringForKey:@"roleName"];
    kUserInfo.CompanyEmail = [userInfo objectFormatStringForKey:@"companyEmail"];
    kUserInfo.WhetherOnline = [userInfo objectFormatStringForKey:@"WhetherOnline"];
    kUserInfo.Telephone = [userInfo objectFormatStringForKey:@"Telephone"];
    
    //保存用户登录信息
    BOOL isSaveSuccess = [NSKeyedArchiverUserLogin saveUserLoginData:kUserInfo];
    if (isSaveSuccess) {
        [JPushHttpService deviceStateRegisterChange];//注册设备RegistrationID
        
        NSMutableArray *newControllers = [NSMutableArray array];
        MainBodyViewController *viewController = [[MainBodyViewController alloc] init];
        [newControllers addObject:viewController];
        [self.navigationController setViewControllers:newControllers animated:YES];
        
    } else {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"登录失败，请尝试再次登录" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        alert.alertViewStyle=UIAlertViewStyleDefault;
        [alert show];
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma -mark IBAction Event02
- (IBAction)loginButtonEvent:(id)sender
{
    [self connectNetworkBeforeChecking];
}

- (IBAction)checkIPButtonEvent:(id)sender
{
    NetworkSettingViewController *viewController = [[NetworkSettingViewController alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
}

@end
